<template>
  
  <view class="order-content">
    <view class="release-contwnt">
      <!-- 顶部分类：沿用原 up-tabbar 样式与图标切换 -->
      <up-tabbar
      :value="tabbarVal"
      @change="onTabbarChange"
      :fixed="false"
      :border="false"
      :placeholder="true"
      :safeAreaInsetBottom="false"
    >
      <up-tabbar-item
        class="tabbar-item"
        :text="item.text"
        v-for="(item, index) in tabbarList"
        :key="index"
      >
        <template #active-icon>
          <up-image
            v-if="tabbarVal !== index"
            width="30px"
            height="30px"
            class="u-page__item__slot-icon"
            :src="`../../static/assets/img/order${index + 1}.png`"
          ></up-image>
          <up-image
            v-else
            width="30px"
            height="30px"
            class="u-page__item__slot-icon"
            :src="`../../static/assets/img/order-${index + 1}.png`"
          ></up-image>
        </template>
        <template #inactive-icon>
          <up-image
            v-if="tabbarVal !== index"
            width="30px"
            height="30px"
            class="u-page__item__slot-icon"
            :src="`../../static/assets/img/order${index + 1}.png`"
          ></up-image>
          <up-image
            width="30px"
            v-else
            height="30px"
            class="u-page__item__slot-icon"
            :src="`../../static/assets/img/order-${index + 1}.png`"
          ></up-image>
        </template>
      </up-tabbar-item>
    </up-tabbar>
      <!-- 三按钮：位于分类导航下方 -->
      <view class="release" style="margin-top: 10px;">
        <view class="button">
          <up-button
            shape="circle"
            text="我的任务"
            :type="modelIndex == 1 ? 'primary' : 'info'"
            @click="releaseTask(1)"
          ></up-button>
        </view>
        <view class="button">
          <up-button
            shape="circle"
            :type="modelIndex == 2 ? 'primary' : 'info'"
            text="可接任务"
            @click="releaseTask(2)"
          ></up-button>
        </view>
        <view class="button">
          <up-button
            shape="circle"
            :type="modelIndex == 3 ? 'primary' : 'info'"
            text="发布任务"
            @click="releaseTask(3)"
          ></up-button>
        </view>
      </view>
    </view>
    <view class="order-item" v-if="modelIndex == 1">
      <view class="for-item" v-if="startTaskList.length">
        <view v-for="(item, index) in startTaskList" :key="index" class="item-task">
          <text class="task">进行中的任务</text>
          <view class="start-time">
            <view>
              <view class="order-status">进行中</view>
              <view class="startTime">任务开始时间：{{ item.task?.createTime || item.startTime || item.executionStartTime }}</view>
              <view class="contact-phone">联系电话：{{ item.task?.contactPhone || item.contactPhone || '暂无' }}</view>
            </view>
            <up-image
              :show-loading="true"
              :src="getImageUrl(item.task?.taskImages)"
              radius="4"
              width="80px"
              height="80px"
            ></up-image>
          </view>
          <view class="task-message">{{ item.task?.taskDescription || item.taskDescription || item.taskMessage }}</view>
        </view>
      </view>
      <view class="empty-img" v-else>
        <up-image
          width="100px"
          height="60px"
          class="u-page__item__slot-icon"
          :src="`../../static/assets/img/empty.png`"
        ></up-image>
        <view class="empty-text">暂无内容</view>
      </view>
    </view>
    <view class="order-item" v-else>
      <view class="for-item" v-if="acceptableTasks.length">
        <view v-for="(item, index) in acceptableTasks" :key="index" class="item-task">
          <text class="task">可接任务</text>
          <view class="start-time">
            <view>
              <view class="order-status">待接单</view>
              <view class="startTime">发布日期：{{ item.createTime }}</view>
              <view class="contact-phone">联系电话：{{ item.contactPhone || '暂无' }}</view>
            </view>
            <up-image
              :show-loading="true"
              radius="4"
              :src="getImageUrl(item.taskImages)"
              width="80px"
              height="80px"
            ></up-image>
          </view>
          <view class="task-message">{{ item.taskDescription }}</view>
          <view class="accept-orders">
            <text>￥{{ item.budgetMax }}</text>
            <view class="button">
              <up-button
                type="primary"
                text="接单"
                @click="acceptRrders(item)"
              ></up-button>
            </view>
          </view>
        </view>
      </view>
      <view class="empty-img" v-else>
        <up-image
          width="100px"
          height="60px"
          class="u-page__item__slot-icon"
          :src="`../../static/assets/img/empty.png`"
        ></up-image>
        <view class="empty-text">暂无内容</view>
      </view>
    </view>


  
  <up-modal :show="showModal" title="发布任务" :showConfirmButton="false">
    <view class="slot-modal">
      
      <view style="display: flex;margin-bottom: 20px;">
        <!-- <view class="u-page__tag-item" v-for="(item, index) in radios" :key="index">
          <up-tag :text="`选项${index + 1}`" :plain="!item.checked" :name="index"
            @click="radioClick">
          </up-tag>
        </view> -->
        <view class="category-select">
          <text class="label">分类</text>
          <select v-model="cateId" @change="selectItem" class="select-input">
            <option value="">请选择分类</option>
            <option 
              v-for="item in cateList" 
              :key="item.value" 
              :value="item.value"
            >
              {{ item.text }}
            </option>
          </select>
        </view>
      </view>
      <up-input v-model="dataInfo.tel" placeholder="请输入联系电话" style="margin-bottom: 20px;"></up-input>
      <!--地址，经度纬度，通过地图组件获取-->
      
      <up-input v-model="dataInfo.addr" placeholder="请选择地址" style="margin-bottom: 20px;">

        <template #suffix>
					<up-icon name="map" color="#2979ff" size="28" @click="showMap"></up-icon>
				</template>
      </up-input>
      <up-textarea v-model="dataInfo.message" placeholder="请输入发布信息"></up-textarea>
      <view class="upload">
        <up-upload
          v-model="uploadList"
          autoDelete
          :autoUpload="false"
          @afterRead="afterRead"
          @change="afterRead"
          getVideoThumb
          name="file"
          multiple
          :previewFullImage="true"
        >
          <template #trigger>
            <view class="upload-icon">
              <up-icon name="arrow-upward" color="#1d7cff" size="25px"></up-icon>
              <text>请上传图片</text>
            </view>
          </template>
        </up-upload>

      </view>
      <view class="modal-footer">
        <view class="upbutton"
          ><up-button text="取消" shape="circle" @click="confirm(0)"></up-button
        ></view>
        <view class="upbutton">
          <up-button
            type="primary"
            text="确定"
            shape="circle"
            color="#4d80f0"
            @click="confirm(1)"
          ></up-button>
        </view>
      </view>
    </view>
  </up-modal>
    <up-modal  :show="show">
       <!-- <web-view src="/hybrid/html/mapsearch.html"
          @onPostMessage="handlePostMessage"
          @message="handlePostMessage"
          :webview-styles="webviewStyles">
        </web-view> -->
        <map2></map2>
      </up-modal>
  </view>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getEnabledTaskCategories, getMyOrganization } from '@/api/index';
import { publishSimpleTask, getPublishedTasks, acceptTask, getMyTasks, getTasksByCategory, getAllPublishedTasks } from '@/api/task';
import { uploadSkill } from '@/api/photo';
import { useUserIdentity } from '@/composables/useUserIdentity';
import map2 from "@/pages/test/choicePointPage.vue";

// 用户身份管理
const { 
  isPilot,
  isOrganization,
  isApprovedPilot,
  isApprovedOrganization,
  initUserIdentity
} = useUserIdentity();
    const webviewStyles = { // web-view样式
        width: "95%",
        height: 200,
        top: 150,
        left: '2.5%'
      };

       const   handlePostMessage=(data:any) => {
      console.log(data.detail.data[0], '天地图发来的数据')
    }
const show = ref(false);  
const modelIndex = ref<any>(1);
const showModal = ref<any>(false);
const dataInfo = ref<any>({});
// 响应式数据  
const cateId = ref('')
const cateList = ref([
    {
        label: '分类1',
        value: '1'
    },
    {
        label: '分类2', 
        value: '2'
    },
    {
        label: '分类3',
        value: '3'
    },
])
  
// 方法  
const selectItem = (item: any) => {  
  console.log('选中的分类:', item);
  console.log('当前cateId:', cateId.value);
  
  // up-select组件会自动更新v-model绑定的值
  // 这里我们只需要处理额外的逻辑
};  
// const radios = reactive([
//   { checked: true },
//   { checked: false },
//   { checked: false }
// ]);
 
const fileList = ref<any>([]);
// 顶部分类（保持原 up-tabbar 样式）
const tabbarVal = ref<any>(0);
const tabbarList = ref<any[]>([]);
const startTaskList = ref<any>([]);
const acceptableTasks = ref<any>([]);
const uploadList = ref<any>([]);

// 当前选中的分类ID
const currentCategoryId = ref<number | null>(null);

// 获取完整的图片URL
const getImageUrl = (imagePath: string) => {
  if (!imagePath) return '';
  // 如果已经是完整URL，直接返回
  if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
    return imagePath;
  }
  // 否则添加服务器地址前缀
  return `http://192.168.5.36:8080${imagePath}`;
};

// 分类切换处理函数
const onTabbarChange = async (index: number) => {
  console.log('分类切换，index:', index);
  tabbarVal.value = index;
  
  // 更新当前选中的分类ID
  if (index === 0) {
    // 选择"全部"
    currentCategoryId.value = null;
  } else {
    // 选择具体分类
    const category = cateList.value[index - 1]; // 减1是因为"全部"占了一个位置
    currentCategoryId.value = category ? parseInt(category.value) : null;
  }
  
  console.log('当前分类ID:', currentCategoryId.value);
  
  // 如果当前在"可接任务"页面，需要刷新任务列表
  if (modelIndex.value === 2) {
    await loadTasksByCategory();
  }
};

// 根据分类加载任务
const loadTasksByCategory = async () => {
  try {
    let res: any;
    
    if (currentCategoryId.value === null) {
      // 查询所有任务
      console.log('查询所有已发布任务');
      res = await getAllPublishedTasks({ pageNum: 1, pageSize: 100 });
    } else {
      // 根据分类查询任务
      console.log('根据分类查询任务，分类ID:', currentCategoryId.value);
      res = await getTasksByCategory(currentCategoryId.value, { pageNum: 1, pageSize: 100 });
    }
    
    const rows = res.data?.rows || res.data?.data || [];
    acceptableTasks.value = Array.isArray(rows) ? rows : [];
    console.log('任务列表:', acceptableTasks.value);
    
    if (!acceptableTasks.value.length) {
      uni.showToast({ title: '该分类下暂无可接任务', icon: 'none' });
    }
  } catch (e) {
    console.error('获取任务列表失败:', e);
    uni.showToast({ title: '获取任务列表失败', icon: 'none' });
  }
};

// const radioClick = (name: any) => {
//   radios.forEach((item, index) => {
//     item.checked = index === name;
//   });
// };
const releaseTask = async (index: any) => {
  modelIndex.value = index;
  switch (index) {
    case 1:
      // 查看我的任务 - 所有用户都可以查看
      try {
        const res: any = await getMyTasks({ pageNum: 1, pageSize: 100 });
        const rows = res.data?.rows || res.data?.data || [];
        startTaskList.value = Array.isArray(rows) ? rows : [];
        console.log('我的任务列表:', startTaskList.value);
        if (!startTaskList.value.length) {
          uni.showToast({ title: '暂无进行中的任务', icon: 'none' });
        }
      } catch (e) {
        console.error('获取我的任务失败:', e);
        uni.showToast({ title: '获取我的任务失败', icon: 'none' });
      }
      break;
    case 2:
      // 可接任务 - 所有用户都可以查看任务列表
      await loadTasksByCategory();
      break;
    case 3:
      // 发布任务 - 检查是否为组织方
      console.log('=== 发布任务权限检查 ===');
      console.log('isOrganization.value:', isOrganization.value);
      console.log('isApprovedOrganization.value:', isApprovedOrganization.value);
      
      if (!isOrganization.value) {
        console.log('用户不是组织方');
        uni.showToast({ 
          title: '只有组织方才能发布任务，请先注册组织信息', 
          icon: 'none',
          duration: 3000
        });
        return;
      }
      if (!isApprovedOrganization.value) {
        console.log('组织方未通过审核');
        uni.showToast({ 
          title: '组织信息未通过审核，无法发布任务', 
          icon: 'none',
          duration: 3000
        });
        return;
      }
      
      console.log('权限检查通过，打开发布任务弹窗');
      // 打开发布任务弹窗
      dataInfo.value = {};
      showModal.value = true;
      break;
    default:
  }
};
const confirm = async (index: Number) => {
  console.log('=== confirm函数被调用 ===');
  console.log('confirm被调用，index:', index);
  console.log('showModal.value:', showModal.value);
  console.log("dataInfo:", dataInfo.value);
  console.log("cateId:", cateId.value);
  console.log("uploadList:", uploadList.value);
  
  if (index === 0) {
    // 取消按钮
    console.log('用户点击了取消按钮');
    showModal.value = false;
    return;
  }
  
  if (index === 1) {
    // 确定按钮 - 发布任务
    console.log('用户点击了确定按钮，开始验证...');
    try {
      // 临时跳过验证，直接测试API调用
      console.log('跳过验证，直接测试API调用...');
      
      // 准备发布数据
      const taskData = {
        categoryId: parseInt(cateId.value) || 1, // 如果没有选择分类，默认使用1
        taskDescription: dataInfo.value.message || '测试任务描述',
        taskImages: uploadList.value.map((item: any) => {
          console.log('处理图片项:', item);
          console.log('item.url:', item.url);
          console.log('item.response?.msg:', item.response?.msg);
          console.log('item.response?.data:', item.response?.data);
          return item.url || item.response?.msg || item.response?.data;
        }).filter(Boolean).join(','), // 图片URL用逗号分隔
        location: dataInfo.value.addr || '', // 地址名称
        latitude: dataInfo.value.latitude || '', // 纬度
        longitude: dataInfo.value.longitude || '' // 经度
      };
      
      console.log('准备发布任务，数据:', taskData);
      console.log('uploadList.value:', uploadList.value);
      console.log('taskImages字段值:', taskData.taskImages);
      console.log('地址信息:', {
        location: taskData.location,
        latitude: taskData.latitude,
        longitude: taskData.longitude
      });
      
      // 调用发布接口
      const response: any = await publishSimpleTask(taskData);
      
      if (response.data.code === 200) {
        uni.showToast({
          title: '任务发布成功',
          icon: 'success'
        });
        
        // 关闭弹窗
        showModal.value = false;
        
        // 清空表单数据
        dataInfo.value = {};
        cateId.value = '';
        uploadList.value = [];
        
        // 可以在这里刷新任务列表
        console.log('任务发布成功，响应:', response.data);
      } else {
        uni.showToast({
          title: response.data.msg || '任务发布失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('发布任务失败:', error);
      uni.showToast({
        title: error.data?.msg || error.errMsg || '发布任务失败',
        icon: 'none'
      });
    }
  }
};

const acceptRrders = async (item: any) => {
  console.log('接单任务:', item);
  
  // 检查是否为飞手
  if (!isPilot.value) {
    uni.showToast({ 
      title: '只有飞手才能接任务，请先注册飞手信息', 
      icon: 'none',
      duration: 3000
    });
    return;
  }
  
  // 检查飞手是否已通过审核
  if (!isApprovedPilot.value) {
    uni.showToast({ 
      title: '飞手档案未通过审核，无法接单', 
      icon: 'none',
      duration: 3000
    });
    return;
  }
  
  try {
    const response: any = await acceptTask(item.taskId);
    
    if (response.data.code === 200) {
      uni.showToast({
        title: "接单成功",
        icon: "success",
      });
      
      // 接单成功后，刷新可接任务列表
      await loadTasksByCategory();
    } else {
      uni.showToast({
        title: response.data.msg || "接单失败",
        icon: "none",
      });
    }
  } catch (error: any) {
    console.error('接单失败:', error);
    uni.showToast({
      title: error.data?.msg || error.errMsg || "接单失败",
      icon: "none",
    });
  }
};


const afterRead = async (event: any) => {
  console.log('=== afterRead函数被调用 ===');
  console.log('照片选择后触发，event:', event);
  console.log('event.file:', event.file);
  console.log('event.name:', event.name);
  console.log('event.index:', event.index);
  
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let lists = [].concat(event.file) as any;
  let fileListLen = uploadList.value.length;
  
  console.log('lists:', lists);
  console.log('fileListLen:', fileListLen);
  
  // 设置上传状态
  lists.map((item: any) => {
    console.log('添加文件到uploadList:', item);
    uploadList.value.push({
      ...item,
      status: "uploading",
      message: "上传中",
    });
  });
  
  console.log('设置上传状态后的uploadList:', uploadList.value);
  
  // 逐个上传文件
  for (let i = 0; i < lists.length; i++) {
    try {
      console.log('开始上传文件:', lists[i].url);
      const result: any = await uploadSkill(lists[i].url);
      
      console.log('上传成功，result:', result);
      
      let item = uploadList.value[fileListLen];
      uploadList.value.splice(fileListLen, 1, {
        ...item,
        status: "success",
        message: "",
        url: result.msg, // 后端返回的图片URL在msg字段中
        response: result
      });
      
      console.log('文件上传成功:', result);
      console.log('更新后的uploadList:', uploadList.value);
      fileListLen++;
    } catch (error: any) {
      console.error('文件上传失败:', error);
      
      let item = uploadList.value[fileListLen];
      uploadList.value.splice(fileListLen, 1, {
        ...item,
        status: "failed",
        message: error.msg || "上传失败",
      });
      
      uni.showToast({
        title: error.msg || '图片上传失败',
        icon: 'none'
      });
      fileListLen++;
    }
  }
};
const deletePic = (event: any) => {
  fileList.value.splice(event.index, 1);
  dataInfo.value = dataInfo.value.att.filter((item: any) => {
    return item.fileName != event.file.name;
  });
};


const showMap = ()=>{
  show.value = true;
}

const selpoint = (v: any)=>{
   console.log('选中的地址信息:', v)
   
   // 保存地址信息到dataInfo
   if (v) {
     dataInfo.value.addr = v.name || '';  // 地址名称
     
     // 从location对象中获取经纬度
     if (v.location) {
       dataInfo.value.latitude = v.location.lat || '';  // 纬度
       dataInfo.value.longitude = v.location.lon || '';  // 经度
     }
     
     // 或者从lonlat字符串中解析经纬度
     if (v.lonlat && v.lonlat.includes(',')) {
       const [lon, lat] = v.lonlat.split(',');
       dataInfo.value.latitude = lat || '';
       dataInfo.value.longitude = lon || '';
     }
     
     dataInfo.value.lonlat = `${dataInfo.value.longitude},${dataInfo.value.latitude}`;  // 经纬度组合
     
     console.log('保存的地址信息:', {
       addr: dataInfo.value.addr,
       latitude: dataInfo.value.latitude,
       longitude: dataInfo.value.longitude,
       lonlat: dataInfo.value.lonlat
     });
   }
   
   show.value = false;
}

uni.$on('choiceAddressPoi',selpoint)

// 挂载时拉取分类，填充到 tabbarList；首项"全部"
onMounted(async () => {
  console.log('=== onMounted开始执行 ===');
  
  // 初始化用户身份信息
  await initUserIdentity();
  
  try {
    console.log('开始调用getEnabledTaskCategories接口...');
    const res: any = await getEnabledTaskCategories();
    console.log('getEnabledTaskCategories响应:', res);
    console.log('res.data:', res.data);
    console.log('res.data?.data:', res.data?.data);
    
    const list = Array.isArray(res.data?.data) ? res.data.data : [];
    console.log('解析后的list:', list);
    
    const tabs = [{ text: '全部' }].concat(list.map((it: any) => ({ text: it.categoryName })));
    tabbarList.value = tabs;
    console.log('设置tabbarList:', tabbarList.value);
    
    // 发布任务弹窗-分类下拉数据
    cateList.value = list.map((it: any) => ({ 
      text: it.categoryName, 
      value: it.categoryId
    }));
    console.log('设置cateList:', cateList.value);
    
    // 设置默认选中第一个分类
    if (cateList.value.length > 0) {
      cateId.value = cateList.value[0].value;
      console.log('设置默认分类:', cateList.value[0]);
    } else {
      console.log('没有分类数据，cateList为空');
    }
    
    // 页面加载时自动获取我的任务
    try {
      console.log('页面加载，自动获取我的任务...');
      const res: any = await getMyTasks({ pageNum: 1, pageSize: 100 });
      const rows = res.data?.rows || res.data?.data || [];
      startTaskList.value = Array.isArray(rows) ? rows : [];
      console.log('我的任务列表:', startTaskList.value);
    } catch (e) {
      console.error('获取我的任务失败:', e);
      startTaskList.value = [];
    }
    
    
  } catch (e) {
    console.error('获取分类数据失败:', e);
    tabbarList.value = [{ text: '全部' }];
    cateList.value = [];
  }
});
</script>
<style lang="scss" scoped>
.order-content {
  height: 100vh;
  overflow: auto;
  padding-bottom: 100px;
  background-color: #f5f7fa;
  
  .category-select {
    margin-bottom: 20px;
    
    .label {
      display: block;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
    }
    
    .select-input {
      width: 100%;
      height: 40px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      background-color: #fff;
      
      &:focus {
        border-color: #409eff;
        outline: none;
      }
    }
  }
  .release-contwnt {
    padding: 15px;
  }
  .release {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    background-color: #eeeeef;
    padding: 5px;
    border-radius: 30px;
    .button {
      width: 120px;
      &:not(:first-child) {
        margin-left: 10px;
      }
    }
  }
}
.order-item {
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  text {
    font-size: 18px;
    font-weight: bold;
    color: #000;
  }
  .for-item {
    .item-task {
      padding: 10px;
      border-radius: 4px;
      background-color: white;
      color: #aaabaf;
      &:not(:first-child) {
        margin-top: 10px;
      }
      .order-status {
        font-weight: bold;
        padding: 5px 0;
        color: #353535;
      }
      .start-time {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-top: 5px;
        .startTime {
          font-size: 14px;
        }
        .contact-phone {
          font-size: 14px;
          color: #666;
          margin-top: 2px;
        }
      }
    }
    .accept-orders {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 10px;
      text {
        color: #ff3c26;
      }
      .button {
        width: 100px;
      }
    }
    .task-message {
      padding-top: 10px;
      text-indent: 2ch;
      white-space: pre-wrap;
      color: #000;
    }
  }
  .task {
    display: block;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 5px;
    margin-bottom: 5px;
  }
}
.slot-modal {
  width: 100%;
  display: flex;
  flex-direction: column;
  .rate {
    display: flex;
    margin: 10px 0;
  }
  .modal-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 20px -10px 0px -10px;
    .upbutton {
      margin: 0 10px;
      width: 50%;
    }
  }
}

.upload {
  margin-top: 20px;
  .upload-icon {
    background-color: #eef6ff;
    color: #1677ff;
    font-size: 14px;
    border-radius: 6px;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}

.empty-img {
  display: flex;
  flex-direction: column;
  align-items: center;
  .empty {
    width: 100px;
    height: 59px;
  }
  .empty-text {
    color: #999999;
    margin-top: 20px;
  }
}
</style>
<style lang="scss">
.u-tabbar {
  .u-tabbar-item {
    width: 50px !important;
  }
}

.u-page__tag-item {
    margin-right: 20px;
  }
</style>
